package ext.vpde.cadvaulting.migration;

import java.io.BufferedReader;
import java.util.Calendar;
import java.util.Hashtable;

import ext.vpde.cadvaulting.util.WINDSQL;
import wt.epm.EPMApplicationType;
import wt.epm.EPMAuthoringAppType;
import wt.epm.EPMDocument;
import wt.epm.EPMDocumentMaster;
import wt.epm.EPMDocumentType;
import wt.fc.*;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.series.MultilevelSeries;
import wt.vc.VersionInfo;

/*
 * CreateEPMDocs reads a file containing all the iterations and their metadata, of CAD Documents 
 * from Product Center and creates EPMDocument objects in Windchill.
 */

public class CreateEPMDocs {

	public static void main ( String [] args ) {
		if (args.length != 3) {
			System.out.println("\nUsage: java.ext.vpde.cadvaulting.CreateEPMDocs adminid adminpw loadfile");
		} else {
			// Login to windchill
			if (LoadUtil.loginRemote(args[0],args[1])) {
				System.out.println("BEGIN CREATE EPM DOCS: " + Calendar.getInstance().getTime());
				try {
					// open a connection to oracle and leave it open throughout this load
					WINDSQL.openConnection();
					
					// open the input file
					BufferedReader file = LoadUtil.openInputFile(args[2]);
					if (file != null) {
						// read each line in the input file until we get to the end
						String s = file.readLine();
						int lineNumber = 0;
						while (s!= null && s.length() > 0) {
							LoadUtil.printProgress(lineNumber++);
							// build a hashtable of all the columns in each line
							Hashtable ht = LoadUtil.processInputLine(s);
							// test to see if the document exists, if it doesnt, then create it.
							if (!WINDSQL.documentExists(ht.get("CADNAME").toString())) {
								//System.out.println("CREATING " + ht.get("CADNAME").toString());
								createDocument(ht);
							} else {
								//System.out.println(ht.get("CADNAME").toString() + " ALREADY EXISTS");
							}
							s = file.readLine();
						}
					} else {
						System.out.println("UNABLE TO OPEN THE FILE: " + args[2]);
					}
					
					// we are done, so close the oracle connection
					WINDSQL.closeConnection();
				} catch (Exception e) { LoadUtil.printException("CreateEPMDocs.main", e); }
				System.out.println("-END- CREATE EPM DOCS: " + Calendar.getInstance().getTime());
			}
		}
    }
	
	/*
	 * Create an EPM document object using the data from the input file
	 */
	
    public static void createDocument(Hashtable ht) {   	
    	
    	String CADName    = ht.get("CADNAME").toString();
    	String version    = ht.get("VERSION").toString();
    	String iteration  = ht.get("ITERATION").toString();
    	String docName    = ht.get("DOCNAME").toString();
    	String docType    = ht.get("DOCTYPE").toString();
    	String subType    = ht.get("SUBTYPE").toString();
    	String contType   = ht.get("CONTAINERTYPE").toString();
    	String contName   = ht.get("CONTAINERNAME").toString();
    	String folderName = ht.get("FOLDERNAME").toString();
    	String state      = ht.get("STATE").toString();
    	int ftStatus      = Integer.parseInt(ht.get("FTSTATUS").toString());
 
    	try {
    		
    		// get the container from the input file for this cad doc
    		WTContainer wtcontainer = LoadUtil.getContainer(contType,contName);
    		WTContainerRef wtcr = WTContainerRef.newWTContainerRef(wtcontainer);
    		//System.out.println("USING CONTAINER: " + wtcr.getName());
    		
    		// instantiate a new object and it master
    		EPMDocumentMaster docMaster = new EPMDocumentMaster();
    		EPMDocument doc = new EPMDocument();
		
    		// some file names might be longer than the document number allowance.
    		if (CADName.length() < 33) docMaster.setNumber(CADName.toUpperCase());
    		
    		// set the master's attributes
    		docMaster.setName(docName);
    		docMaster.setContainerReference(wtcr);
    		docMaster.setCADName(CADName);
    		docMaster.setAuthoringApplication(EPMAuthoringAppType.toEPMAuthoringAppType("PROE"));
    		docMaster.setOwnerApplication(EPMApplicationType.toEPMApplicationType("EPM"));
    		docMaster.setDocType(EPMDocumentType.toEPMDocumentType(docType));

    		// set the iteration's attributes
    		doc.setMaster(docMaster);
    		doc.setAuthoringAppVersion(LoadUtil.getAuthoringAppVersion());
    		doc.setDomainRef(wtcontainer.getSystemDomainReference());
    		doc.setFamilyTableStatus(ftStatus);
    		
    		// set the version from the input
    		MultilevelSeries mls = MultilevelSeries.newMultilevelSeries("wt.series.HarvardSeries.FileBased",version);
			doc.setVersionInfo(VersionInfo.newVersionInfo(mls));
			//System.out.println("SETTING VERSION: " + version);
			
			// assign the folder if there is one
   			Folder folder = FolderHelper.service.getFolder(folderName, wtcr);
   			FolderHelper.assignLocation((FolderEntry)doc, folder);
   			//System.out.println("SETTING FOLDER: " + folder.getName());
            
   			// create the object
   			Persistable p = PersistenceHelper.manager.save(doc);
   			System.out.println(CADName + " CREATED");
   			
   			// update attributes using JDBC
   			String ida2a2 = LoadUtil.getIdFromPersistable(p);
   			WINDSQL.updateIteration(ida2a2,iteration);
   			WINDSQL.updateState(ida2a2,state);
   			WINDSQL.updateSubType(ida2a2,subType);

   		} catch(Exception e) { LoadUtil.printException("CreateEPMDocs.createDocument", e); }
    }
}